package com.jyxd.web.controller.basic;

import com.alibaba.fastjson.JSON;
import com.jyxd.web.data.basic.MedOrderExec;
import com.jyxd.web.data.basic.MedOrderExecSync;
import com.jyxd.web.data.basic.NursingRecord;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.*;
import com.jyxd.web.service.dictionary.CommentItemService;
import com.jyxd.web.util.HttpCode;
import com.jyxd.web.util.JsonArrayValueProcessor;
import com.jyxd.web.util.UUIDUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/medOrderExec")
public class MedOrderExecController {

    private static Logger logger = LoggerFactory.getLogger(MedOrderExecController.class);

    @Autowired
    private MedOrderExecService medOrderExecService;

    @Autowired
    private InputAmountService inputAmountService;

    @Autowired
    private InOutAmountService inOutAmountService;

    @Autowired
    private MedOrderExecSyncService medOrderExecSyncService;

    @Autowired
    private NursingRecordService nursingRecordService;

    @Autowired
    private CommentItemService commentItemService;

    @Autowired
    private MedOrderExecRecordService medOrderExecRecordService;


    /**
     * 增加一条医嘱执行表记录
     *
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody MedOrderExec medOrderExec) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        medOrderExec.setId(UUIDUtil.getUUID());
        medOrderExec.setCreateTime(new Date());
        medOrderExecService.insert(medOrderExec);
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg", "添加成功");
        return json.toString();
    }

    /**
     * 更新医嘱执行表记录状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "更新失败");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            MedOrderExec medOrderExec = medOrderExecService.queryData(map.get("id").toString());
            if (medOrderExec != null) {

                medOrderExecService.update(medOrderExec);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑医嘱执行表记录单
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        if (map != null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")) {
            MedOrderExec medOrderExec = medOrderExecService.queryData(map.get("id").toString());
            if (medOrderExec != null) {

                medOrderExecService.update(medOrderExec);
                json.put("msg", "编辑成功");
            } else {
                json.put("msg", "编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除医嘱执行表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (map.containsKey("id")) {
            MedOrderExec medOrderExec = medOrderExecService.queryData(map.get("id").toString());
            if (medOrderExec != null) {

                medOrderExecService.update(medOrderExec);
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询医嘱执行表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            MedOrderExec medOrderExec = medOrderExecService.queryData(map.get("id").toString());
            if (medOrderExec != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(medOrderExec));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询医嘱执行表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("start")) {
            int totalCount = medOrderExecService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<MedOrderExec> list = medOrderExecService.queryList(map);
        if (list != null && list.size() > 0) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list, jsonConfig));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 医嘱处理--医嘱列表--批量同步到入量
     * 修改为可以同步多条医嘱信息
     */
    @RequestMapping(value = "/synchronousInPutS", method = RequestMethod.POST)
    @ResponseBody
    public String synchronousInPutS(@RequestBody(required = false) List<String> idList, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "同步失败");
        User user = (User) session.getAttribute("user");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        double inSum = 0;
        String medOrderInfos = "";
        String orderIds = "";
        String useMode = "";
        int i = 0;
        List<MedOrderExec> list = new ArrayList<MedOrderExec>();
        if (idList.size() > 0) {
            try {
                //根据医嘱主键查询医嘱列表
                list = medOrderExecService.queryListByOrderIds(idList);
                for (String orderId : idList) {
                    orderIds = orderId + ",";
                    useMode = list.get(0).getUseMode();
                }
                if (CollectionUtils.isEmpty(list)) {
                    json.put("msg", "同步成功,暂无数据");
                    json.put("code", HttpCode.OK_CODE.getCode());
                }
                for (MedOrderExec medOrderExec : list) {
                    //根据主医嘱ordercode 查询此条主医嘱下的所有副医嘱
                    List<MedOrderExec> medOrderExecsList = medOrderExecService.queryDataByOrderSubNo(medOrderExec);
                    if (!CollectionUtils.isEmpty(medOrderExecsList)) {
                        for (MedOrderExec medOrder : medOrderExecsList) {
                            if (1 != medOrder.getDrugType()) {
                                medOrderInfos = medOrderInfos + medOrder.getOrderName() + ";";
                            } else {
                                if ("口服".equals(useMode) && idList.size() > 1) {
                                    i = i + 1;
                                    medOrderInfos = medOrderInfos + i + "." + medOrder.getOrderName() + medOrder.getDosage() + medOrder.getDosageUnits() + ";\n";
                                } else {
                                    medOrderInfos = medOrderInfos + medOrder.getOrderName() + medOrder.getDosage() + medOrder.getDosageUnits() + ";";
                                }
                                if (StringUtils.isNotEmpty(medOrder.getDosage()) && "ml".equals(medOrder.getDosageUnits())) {
                                    inSum = inSum + Double.valueOf(medOrder.getDosage());
                                }
                            }
                        }
                    }
                }
                if (!StringUtils.equals(medOrderInfos, "")) {
                    medOrderInfos = medOrderInfos.substring(0, medOrderInfos.length() - 1);
                }
                if (!StringUtils.equals(orderIds, "")) {
                    orderIds = orderIds.substring(0, orderIds.length() - 1);
                }
                dataMap.put("id", orderIds);
                dataMap.put("allowanceDosage", inSum == 0 ? "" : inSum);
                dataMap.put("orderName", medOrderInfos);
                dataMap.put("useMode", useMode);
                json.put("data", dataMap);
                json.put("msg", "同步成功");
                json.put("code", HttpCode.OK_CODE.getCode());
            } catch (Exception e) {
                logger.info("医嘱处理--医嘱列表--同步到入量 synchronousInPuts:" + e);
                e.printStackTrace();
            }
        }
        return json.toString();
    }

    /**
     * 医嘱处理--医嘱列表--同步到护理措施
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/synchronousNursingRecord", method = RequestMethod.POST)
    @ResponseBody
    public String synchronousNursingRecord(@RequestBody(required = false) Map<String, Object> map, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "同步失败");
        try {
            User user = (User) session.getAttribute("user");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            //新增一条护理措施记录 保存内容
            NursingRecord nursingRecord = new NursingRecord();
            nursingRecord.setId(UUIDUtil.getUUID());
            nursingRecord.setCreateTime(new Date());
            nursingRecord.setDataTime(format.parse(map.get("dataTime").toString()));
            nursingRecord.setVisitId(map.get("visitId").toString());
            nursingRecord.setVisitCode(map.get("visitCode").toString());
            nursingRecord.setPatientId(map.get("patientId").toString());
            nursingRecord.setStatus(1);
            if (user != null) {
                nursingRecord.setOperatorCode(user.getLoginName());
            }
            nursingRecord.setCode("nursingRecordContent");//nursingRecordContent 默认为 医嘱列表同步到护理措施  内容
            nursingRecord.setContent(map.get("nursingRecordContent").toString());
            nursingRecordService.insert(nursingRecord);

            //新增一条护理措施记录 保存签名
            NursingRecord nursingRecord1 = new NursingRecord();
            nursingRecord1.setId(UUIDUtil.getUUID());
            nursingRecord1.setCreateTime(new Date());
            nursingRecord1.setDataTime(format.parse(map.get("dataTime").toString()));
            nursingRecord1.setVisitId(map.get("visitId").toString());
            nursingRecord1.setVisitCode(map.get("visitCode").toString());
            nursingRecord1.setPatientId(map.get("patientId").toString());
            nursingRecord1.setStatus(1);
            if (user != null) {
                nursingRecord1.setOperatorCode(user.getLoginName());
            }
            nursingRecord1.setCode("signature");//signature 默认为 医嘱列表同步到护理措施记录  签名
            nursingRecord1.setContent(map.get("signature").toString());
            nursingRecordService.insert(nursingRecord1);


            //新建一条 医嘱执行同步表 记录
            MedOrderExecSync medOrderExecSync = new MedOrderExecSync();
            medOrderExecSync.setId(UUIDUtil.getUUID());
            medOrderExecSync.setCreateTime(new Date());
            medOrderExecSync.setDataTime(format.parse(map.get("dataTime").toString()));
            medOrderExecSync.setDefaultTimePoint(format.parse(map.get("dataTime").toString()));
            if (user != null) {
                medOrderExecSync.setOperatorCode(user.getLoginName());
            }
            medOrderExecSync.setOrderNo(map.get("orderType").toString());
            medOrderExecSync.setPatientId(map.get("patientId").toString());
            medOrderExecSync.setNurseCode(map.get("signature").toString());
            medOrderExecSync.setContent(map.get("nursingRecordContent").toString());
            medOrderExecSync.setVisitId(map.get("visitId").toString());
            medOrderExecSync.setVisitCode(map.get("visitCode").toString());
            medOrderExecSyncService.insert(medOrderExecSync);

            json.put("msg", "同步成功");
            json.put("code", HttpCode.OK_CODE.getCode());
        } catch (Exception e) {
            logger.info("医嘱处理--医嘱列表--同步到护理措施记录 :" + e);
        }
        return json.toString();
    }

    /**
     * 根据条件分页查询医嘱执行表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public String getList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        String timeOrder = (String) map.get("orderTime");
        map.put("timeOrder", timeOrder);
        //判断状态是否选择，如果没选择 ，查询的是此人所有状态的医嘱，把orderstatus条件删除掉
        if (map != null && map.containsKey("orderStatus")) {
            String orderStatus = map.get("orderStatus").toString();
            if (orderStatus.equals("")) {
                map.remove("orderStatus");
            }
        }
        if (map != null && map.containsKey("repeatIndicator")) {
            String repeatIndicator = map.get("repeatIndicator").toString();
            //判断是否为查询长期医嘱，如果是，把时间条件删除，查询此人所有的长期医嘱
            if (StringUtils.isEmpty(repeatIndicator) || repeatIndicator.equals("1")) {
                map.remove("orderTime");
                //判断是否为查询全部
            }
            /*else if(repeatIndicator.equals("5")){
                map.remove("orderTime");
                map.remove("drugType");
                map.remove("repeatIndicator");
            }
            //其他时，如果是，把是否为药嘱条件和时间条件去掉，查询查询其他不为药嘱的情况
            else if(repeatIndicator.equals("3")){
                map.put("drugType",0);
                map.remove("orderTime");
                map.remove("repeatIndicator");
            }*/

        } else if (map == null || !map.containsKey("repeatIndicator")) {
            map.remove("orderTime");
        }
        if (map != null && map.containsKey("start")) {
            //  int totalCount = medOrderExecService.getNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            //  json.put("totalCount", totalCount);
        }

        List<Map<String, Object>> list = medOrderExecService.getList(map);

        if (map != null && map.containsKey("start")) {
            map.remove("start");
            map.remove("size");
            List<Map<String, Object>> Countlist = medOrderExecService.getList(map);
            int totalCount = Countlist.size();
            json.put("totalCount", totalCount);
        }

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).put("hasChildren", true);
            }

            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list, jsonConfig));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 获取药嘱（护理单三同步时候用）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getDrugList", method = RequestMethod.POST)
    @ResponseBody
    public String getDrugList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");

        String timeOrder = (String) map.get("orderTime");
        map.put("timeOrder", timeOrder);

        //判断状态是否选择，如果没选择 ，查询的是此人所有状态的医嘱，把orderstatus条件删除掉
        if (map != null && map.containsKey("orderStatus")) {
            String orderStatus = map.get("orderStatus").toString();
            if (orderStatus.equals("")) {
                map.remove("orderStatus");
            }
        }
        if (map != null && map.containsKey("repeatIndicator")) {
            String repeatIndicator = map.get("repeatIndicator").toString();
            //判断是否为查询长期医嘱，如果是，把时间条件删除，查询此人所有的长期医嘱
            if (StringUtils.isEmpty(repeatIndicator) || repeatIndicator.equals("1")) {
                map.remove("orderTime");
                //判断是否为查询全部
            }
            /*else if(repeatIndicator.equals("5")){
                map.remove("orderTime");
                map.remove("drugType");
                map.remove("repeatIndicator");
            }
            //其他时，如果是，把是否为药嘱条件和时间条件去掉，查询查询其他不为药嘱的情况
            else if(repeatIndicator.equals("3")){
                map.put("drugType",0);
                map.remove("orderTime");
                map.remove("repeatIndicator");
            }*/

        } else if (map == null || !map.containsKey("repeatIndicator")) {
            map.remove("orderTime");
        }

        if (map != null && map.containsKey("start")) {
            //  int totalCount = medOrderExecService.getNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            //  json.put("totalCount", totalCount);
        }

        List<Map<String, Object>> list = medOrderExecService.getList(map);

        if (map != null && map.containsKey("start")) {
            map.remove("start");
            map.remove("size");
            List<Map<String, Object>> Countlist = medOrderExecService.getList(map);
            int totalCount = Countlist.size();
            //int totalCount = medOrderExecService.getNum(map);
            json.put("totalCount", totalCount);
        }

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).put("hasChildren", true);
                if (list.get(i).get("useMode").toString().contains("湿化")) {
                    list.remove(i);
                    i -= 1;
                }
            }
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list, jsonConfig));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据父医嘱信息查询子医嘱
     *
     * @return
     */
    @RequestMapping(value = "/getSonOrderList", method = RequestMethod.POST)
    @ResponseBody
    public String getSonOrderList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        JsonConfig jsonConfig = new JsonConfig();
        List<MedOrderExec> medOrderExecslistNull = new ArrayList<>();
        if (CollectionUtils.isEmpty(map)) {
            MedOrderExec medOrderExec = new MedOrderExec();
            medOrderExecslistNull.add(medOrderExec);
            json.put("data", JSON.toJSONString(medOrderExecslistNull));
        } else {
            List<MedOrderExec> medOrderExecslist = medOrderExecService.querySonOrderList(map);
            if (medOrderExecslist != null && medOrderExecslist.size() > 0) {
                for (int a = 0; a < medOrderExecslist.size(); a++) {
                    MedOrderExec medOrder = medOrderExecslist.get(a);
                    if (medOrder.getOrderNo().equals(medOrder.getOrderSubNo())) {
                        medOrderExecslist.remove(a);
                        a -= 1;
                    }
                }
                jsonConfig.registerJsonValueProcessor(Date.class, new JsonArrayValueProcessor());
                json.put("data", JSONArray.fromObject(medOrderExecslist, jsonConfig));
            }
        }
        json.put("msg", "查询成功");
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 判断是医嘱否存在无法计算的的单位
     *
     * @return
     */
    public boolean isUnits(String medOrderInfo) {
        if (medOrderInfo.contains("AXa") || medOrderInfo.contains("g") || medOrderInfo.contains("IU")
                || medOrderInfo.contains("mg") || medOrderInfo.contains("μg") || medOrderInfo.contains("万U")
                || medOrderInfo.contains("万单位") || medOrderInfo.contains("单位")
                || medOrderInfo.contains("片") || medOrderInfo.contains("袋")) {
            return false;
        }
        return true;
    }


}
